<?php
namespace control;
/*
*领料单类
*/

class pickOrderClass extends adIndexClass
{
    private const page = 'pickOrder';
    private const table = 'pick_order';
    private const tableMx = 'pick_order_detail';
    private const title = '领料单';

    /**
     * 字段初始化
     */
    public function fieldInit($fun): array
    {
        switch ($fun) {
            default:
                $tr = [
                    'orderNo'          => [
                        'name'  => "单据编号",
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'line'  => [
                        'name'  => '生产线',
                        'width' => 200,
                    ],
                    'pickId'         => [
                        'name'  => '领料人',
                        'width' => 200,
                    ],
                    'num'          => [
                        'name'  => '数量',
                        'width' => 200,
                    ],
                    'recordDate'          => [
                        'name'  => '单据日期',
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'text'          => [
                        'name'  => '备注',
                        'width' => 200,
                    ],
                    'state'          => [
                        'name'  => '状态',
                        'width' => 200,
                    ]
                ];
        }
        return $tr;
    }

    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    "单据编号" => text(array("name" => "orderNo")),
                    "生产线"   => selectMultiple(["name" => "lineId", 'table' => "product_line", 'sqlId' => 'id', 'where' => "coid = '" . self::$coid . "'", 'sqlField' => 'name']),
                    '领料人' => selectMultiple(["name" => "pickId", 'table' => "staff", 'sqlId' => 'stid', 'sqlField' => 'name']),
                ],
                [
                    "单据日期" => text(array("name" => "createTime", 'laydate' => ['type' => 'date', 'range' => '~'])),
                    "状态" => select(["name" => "state", 'option' => ['草稿', '待确认', '已确认']]),
                ]
            ]
        ],1);
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

    /*列表-查询条件*/
    public function home()
    {
        $html = $this->homeOptions(false);
        //控件
        $button = "";
        $url = root . "control/adIndex.html?cla=" . self::page;
        if ($this->power(self::page, "edit")) {
            $button .= "<span onclick=\"newIframe('" . self::title . "详情','" . $url . "&fun=edit')\" class='spanButton'>新增</span>\n";
        }
        if ($this->power(self::page, "del")) {
            $button .= "<span class='spanButton' onclick=\"layer('{$this->get('cla')}', 'operate', {'act': 'del'})\">删除</span>\n";
        }
        if ($this->power(self::page, 'import')) {
            $button .="<span class='spanButton' onclick=\"layer('importTemplate','importFrame',{cla:'".self::page."'})\">导入</span>";
        }
        //返回
        return $this->homeFun($this->search($html, layout: 'pop', toolButton: $button));
    }

    /*客户列表-查询结果*/
    public function homeSearch()
    {
        //like查询数组
        $like = array(
            "orderNo" => $this->post('orderNo'),
        );
        //全等查询数组
        $equal = array(
            "state" => $this->post('state'),
            "pickId" => $this->post('pickId'),
            "lineId" => $this->post('lineId'),
            'coid' => self::$coid
        );
        $and = " and type=0";
        if ($this->post('createTime')) {
            $and .= self::timeComparison($this->post('createTime'), 'date', 'recordDate');
        }
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'recordDate desc,time',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
        //获取查询结果
        $where = search(array("like" => $like, "=" => $equal)) . $and;
        $page = $this->page(array("table" => self::table, "where" => $where, "order" => $orderBy['orderBy']));
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array(
            $this->checkAll("listForm", "listId")
        );
        //获取记录
        $url = root . "control/adIndex.html?cla=" . self::page;
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate = array(
                "box" => array("name" => "listId", "value" => $array['id']),
                "edit" => array("title" => "编辑", "click" => "newIframe('" . self::title . "详情','" . $url . "&fun=edit&id=" . $array['id'] . "')"),
                "detail" => array("title" => self::title . "详情", "click" => "newIframe('" . self::title . "详情','" . $url . "&fun=detail&id=" . $array['id'] . "')"),
                'track' => array("title" => "单据追踪", "click" => "newIframe('单据追踪','" . root . "control/adIndex.html?cla=orderTrack&fun=home&orderType=领料单&id=" . $array['id'] . "')"),
            );
            if ($this->power(self::page, 'print')) {
                $dominate['print'] = array('title' => '打印', 'click' => "window.open('" . root . "control/adIndex.html?cla=" . self::page . "&fun=printPage&id={$array['id']}')");
            }
            if ($array['state'] == '已确认') {
                unset($dominate['edit']);
            }
            $liButton[] = $this->dominate($dominate);
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case 'line':
                        $line = query('product_line', "id = '$array[lineId]'");
                        $row[] = $line['name'];
                        break;
                    case 'num':
                        $num = find(array('table' => self::tableMx, 'where' => "orderId = '$array[id]'", 'sum' => "num"));
                        $row[] = self::lostZero($num, 'numPrecision');
                        break;
                    case 'pickId':
                        $row[] = self::findStaff($array['pickId']);
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        $totalQuery = find([
            'table'  => self::tableMx,
            'single' => " orderId in (select id from ".self::table." where 1=1 {$where}) ",
            'field'  => "ifnull(sum(num),0) as num",
        ]);
        $total    = [
            'num'        => self::lostZero($totalQuery['num'], 'numPrecision'),
        ];
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
            "total"       => $total,
        ));
        //返回
        $json['html'] = $page['hint'] . "<form name='listForm'>" . $li . "</form>" . $page['button'] . clear;
        return json_encode($json, 320);
    }

    /**
     * 下载模板
     */
    public function downloadModel()
    {
        $templateId = $this->get('templateId');
        if (!$this->power(self::page, 'import')) {
            $_SESSION['warn'] = '你还没有导入的权限';
        } else {
            $exampleData[] = [
                '', '2023-02-24', 'SCX001', 'A生产线', 'YM202211030001', '张三', '样例数据', 'YL002', 'B原料', 'CK001', 'A产品仓库', 'kg', 100, 50, '', '测试数据'
            ];
            $excel    = $this->excelHead();
            $fileName = self::title.'导入模板-'.importTemplateClass::getName($templateId).'.xlsx';
            $filePath = $excel->fileName($fileName, 'sheet1');
            $format = new \Vtiful\Kernel\Format($filePath->getHandle());
            $templateField = importTemplateClass::templateField(self::page, 'importFieldInit', id:$templateId);
            $index         = 0;
            foreach ($templateField as $k => $array) {
                if ($array['display']){
                    $backgroundStyle=null;
                    if (importTemplateClass::getIsMustValue($this->importFieldInit(), $array['columnName'])){
                        //必填项判断
                        $backgroundStyle  = $format->background(
                            0xFFC04B
                        )->toResource();
                    }
                    $filePath->insertText(0, $index, $array['aliasName'],'',$backgroundStyle);
                    foreach ($exampleData as $y=>$example){
                        $exampleVal = match ($array['columnName']){
                            '单据编号'=>$example[0],
                            '单据日期'=>$example[1],
                            '生产线编号'=>$example[2],
                            '生产线名称'=>$example[3],
                            '领料人编号'=>$example[4],
                            '领料人名称'=>$example[5],
                            '单据备注'=>$example[6],
                            '物料名称'=>$example[7],
                            '规格型号'=>$example[8],
                            '仓库编码'=>$example[9],
                            '仓库名称'=>$example[10],
                            '单位'=>$example[11],
                            '数量'=>$example[12],
                            '单价'=>$example[13],
                            '批次'=>$example[14],
                            '备注'=>$example[15],
                            default=>'',
                        };
                        $filePath->insertText($y+1, $index, $exampleVal);
                    }
                    $index++;
                }
            }
            $text = $this->control['name'] . "下载了" . self::title . "导入模板";
            $this->logText(["type" => self::page, "text" => $text]);
            $this->excelOutPut($filePath,$fileName);
            exit(0);
        }
        header("Location:" . getenv("HTTP_REFERER"));
    }

    /*数据导入*/
    public function importData()
    {
        $templateId = $this->post('templateId');
        if (!$this->power(self::page, 'import')) {
            $json['warn'] = '你还没有导入的权限';
        } else {
             $fomatArray = [];//导入数据格式同一为TYPE_STRING
            foreach ($this->importFieldInit() as $value){
                $fomatArray[] = \Vtiful\Kernel\Excel::TYPE_STRING;
            }
            $data = $this->importHead(format: $fomatArray);
            $x = 0;
            $text = '';
            $saleOrder = [];
            $headArray = [];
            $row_list=0;
            foreach ($data as $i => $row) {
                $row_list++;
                if ($i==0){
                    $templateField = importTemplateClass::templateField(self::page, 'importFieldInit', id:$templateId);
                    $headArray = importTemplateClass::combinHead($templateField,$row);
                }
                if ($i > 0) {
                    $rowData = formSubArray($row);
                    //只接收模板中选中的字段的值
                    $cell = [];
                    foreach ($headArray as $index=>$headName){
                        $cell[$headName] = $rowData[$index]??'';
                    }
                    //初始化未被模板需要的字段的值
                    foreach ($this->importFieldInit() as $value){
                        $cell[$value['columnName']] = $cell[$value['columnName']]??'';
                    }
                    if (!empty($cell['单据日期'])) {
                        $saleOrder = [];
                        $pickMan = query('staff', "orderNo = '$cell[领料人编号]'");
                        $line = query('product_line', "orderNo = '$cell[生产线编号]' and coid = '" . self::$coid . "'");
                        $field = [
                            'text' => $cell['单据备注'],
                            'lineId' => $line['id'],
                            'pickId' => $cell['领料人编号']?$pickMan['stid']:$line['staffId'],
                            'recordDate' => self::importDateFormat($cell['单据日期']),
                        ];
                        $annotation = [
                            'lineId' => '生产线',
                            'pickId' => '领料人',
                            'recordDate' => '单据日期',
                        ];
                        $rules = [
                            'lineId' => 'required',
                            'pickId' => 'required',
                            'recordDate' => 'required|date',
                        ];
                        $info = query(self::table, "type = 0 and orderNo = '$cell[单据编号]' and coid = '" . self::$coid . "'");
                        // 校验是否符合规则
                        $vt = new \verify();
                        $result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
                        if ($result === false) {
                            $text .= "\n第【{$row_list}】行，" . $vt->getErrs()[0];
                        }elseif(!empty($info['id']) && $info['state'] =='已确认'){
                            $text .= "\n第【{$row_list}】行，此单据已确认，不能再继续编辑";
                        } else {
                            if (empty($info['id'])) {
                                // 新增
                                $userNo = codeTemplateClass::generateCode(self::page, [
                                    'prefix' => 'LLDD' . date('Ymd', strtotime($field['recordDate'])),
                                    'table' => self::table,
                                    'field' => 'orderNo',
                                    'where' => "and coid = '" . self::$coid . "'",
                                ], $field);
                                $field = array_merge($field, [
                                    'id' => suiji(),
                                    'orderNo' => $userNo,
                                    'state' => '草稿',
                                    'coid' => self::$coid,
                                    'stid' => $this->control['stid'],
                                ]);
                                $warn = static::insert([
                                    "table" => self::table,
                                    "field" => $field,
                                ]);
                            } else {
                                $warn = static::update([
                                    "table" => self::table,
                                    "field" => $field,
                                    'where' => "id = '$info[id]'"
                                ]);
                            }
                            if (in_array($warn, ["新增成功", "更新成功"])) {
                                $saleOrder = match ($warn){
                                    '新增成功'=>$field,
                                    default=>$info
                                };
                            } else {
                                $text .= "\n第【{$row_list}】行，编辑主数据失败，" . $warn;
                            }
                        }

                    }
                    if (isset($saleOrder['id']) && !empty($saleOrder['id'])) {
                        $material = query('material', "coid = '" . self::$coid . "' and model = '$cell[规格型号]' and name = '$cell[物料名称]'");
                        if (!in_array($cell['单位'], machiningOrderClass::unitOption($material['id']))) {
                            $text .= "\n第【{$row_list}】行，单位【{$cell['单位']}】不在此物料的可选单位范围内";
                        } else {
                            $warehouse = query('warehouse', "orderNo = '$cell[仓库编码]' and coid = '" . self::$coid . "'");
                            $mx = query(self::tableMx,"materialId = '$material[id]' and orderId = '$saleOrder[id]'");
                            $cell['数量'] = (float)$cell['数量'];
                            $cell['单价'] = (float)$cell['单价'];
                            if (empty($mx['id'])){
                                //明细
                                $mxField = [
                                    'id' => suiji(),
                                    'orderId' => $saleOrder['id'],
                                    'coid' => self::$coid,
                                    'materialId' => $material['id'],
                                    'num' => $cell['数量'],
                                    'price' => $cell['单价'],
                                    'money' => self::formattingFigure($cell['数量']*$cell['单价']),
                                    'batch' => $cell['批次'],
                                    'unit' => $cell['单位'],
                                    'warehouseId' => $warehouse['id'],
                                    'text' => $cell['备注'],
                                ];
                                $warn = static::insert([
                                    "table" => self::tableMx,
                                    "field" => $mxField,
                                ]);
                            }else{
                                //明细
                                $mxField = [
                                    'materialId' => $material['id'],
                                    'num' => $cell['数量'],
                                    'price' => $cell['单价'],
                                    'money' => self::formattingFigure($cell['数量']*$cell['单价']),
                                    'batch' => $cell['批次'],
                                    'unit' => $cell['单位'],
                                    'warehouseId' => $warehouse['id'],
                                    'text' => $cell['备注'],
                                ];
                                $warn = static::update([
                                    "table" => self::tableMx,
                                    "field" => $mxField,
                                    'where'=>"id = '$mx[id]'"
                                ]);
                            }
                            if (in_array($warn, ["新增成功", "更新成功"])) {
                                $text .= "\n第【{$row_list}】行，导入成功";
                                $x++;
                            } else {
                                $text .= "\n第【{$row_list}】行，导入失败：插入数据库失败，" . $warn;
                            }
                        }
                    } else {
                        $text .= "\n第【{$row_list}】行，未找到单据";
                    }
                }
            }
            $total = count($data)-1;
            $json['data'] = [
                'text'=>$text,
                'title'=>"您导入了{$total}条数据，成功{$x}条，失败".($total-$x)."条",
            ];
            $text = $this->control['name'] . '导入了文件：' . $_FILES['file']['name'] . '：' . $text;
            $this->logText(["type" => self::page, "text" => $text]);
            $json['warn'] = 2;
        }
        return json_encode($json,320);
    }

    /**
     * 编辑页
     * @return string
     */
    public function edit(): string
    {
        $id = $this->get('id') ?: suiji();
        $info = query(self::table, " id = '" . $id . "' ");

        $button[] = [
            "name" => "保存为草稿",
            "type" => "点击事件",
            "title" => "保存",
            'fun' => "subForm('" . self::page . "EditForm','" . root . "control/adIndex.html?cla=" . self::page . "&fun=editEdit')"
        ];
        $button[] = [
            'style' => 'li-btn-blue-bg',
            "name" => "保存并提交",
            "type" => "点击事件",
            "title" => "保存",
            'fun' => "subForm('" . self::page . "EditForm','" . root . "control/adIndex.html?cla=" . self::page . "&fun=saveAndCommit')"
        ];
        //仓库
        $result = find(array('table' => 'warehouse', 'field' => 'id,name', 'where' => "coid = '" . self::$coid . "' order by time desc"));
        $tr[] = [
            '',
            '存货分类',
            '物料编码',
            '物料名称',
            '规格型号',
            '单位',
            "<div class='warehouse'><span class='word'>仓库</span>&emsp;" . self::chooseSelect($result['array'], 'warehouseId[]', 'warehouse', callback: 'warehouseCall') . "</div>",
            '批次',
            '批次库存',
            '数量',
            '源单类型',
            '关联源单',
            '备注'
        ];
        $result = find(array('table' => self::tableMx, 'where' => "orderId = '$info[id]' order by list"));
        foreach ($result['array'] as $k=>$array) {
            $material = query('material', " id = '$array[materialId]'");
            $machiningOrderMx = query('machining_order_detail', "id = '$array[sourceId]'");
            $machiningOrder = query('machining_order', "id = '$machiningOrderMx[orderId]'");
            //当前可用库存
            //$inventoryNum = machiningOrderClass::inventory($array['materialId'], $array['unit'], $array['warehouseId']);"<span class='inventory'>" . self::formattingFigure($inventoryNum, 'numPrecision') . "</span>",
            $unitOption = machiningOrderClass::unitOption($material['id']);
            $batchInventory = inventoryBalanceClass::inventoryNum($material['id'], $array['warehouseId'], batch: $array['batch']);
            $batchInventory = machiningOrderClass::material_num_change($material['id'], $material['unit'], $array['unit'], $batchInventory);
            $tr[] = [
                componentClass::tablePperation($k+1,"delTableRow(this);calculateTotal()").
                hidden(array('name' => 'mxId[]', 'value' => $array['id'])) .
                hidden(array('name' => 'materialId[]', 'value' => $array['materialId'])) .
                hidden(array('name' => 'sourceId[]', 'value' => $array['sourceId'])),
                $material['subject'],
                $material['code'],
                $material['name'],
                $material['model'],
                select(array('name' => 'unitDetail[]', 'data' => ['unit' => $array['unit']], 'change' => 'unitChange', 'option' => $unitOption, 'title' => '单位', 'value' => $array['unit'])),
                select(array('name' => 'warehouseId[]','option' => toolOverhaulOutClass::warehouseOption($array['materialId'],$array['unit']),   'change' => 'getInventory',  'title' => '仓库', 'value' => $array['warehouseId'])),
                "<span class='batch'>" . selectMultiple(["name" => "batch[]", 'option' => toolOverhaulOutClass::getBatchOption($material['id'], $array['warehouseId'], unit:$array['unit']), 'title' => '请选择', 'change' => 'getBatchInventory', 'value' => $array['batch']]) . "</span>",
                "<span class='batchInventory'>" . $batchInventory . "</span>",
                text(array('name' => 'num[]', 'other' => self::digitalFiltering('numPrecision')." onblur=\"calculateTotal()\" ", 'value' => self::lostZero($array['num'], 'numPrecision'))),
                $this->orderType($machiningOrder['orderType']),
                $machiningOrder['orderNo'],
                text(array('name' => 'mxText[]', 'class' => 'text textPrice', 'value' => $array['text'])),
            ];
        }
        $total      = [
            9  => "<span id='total_num'>" . self::lostZero(array_sum(array_column((array)$result['array'],'num')),'num') . "</span>",
        ];
        $table = $this->listTable(array('tr' => $tr, 'end' => true, 'total' => $total));
        $but = <<<efo
                <span class="smallButton" onclick="chooseOrder('machiningOrder')">关联生产计划单</span>
                <span class="smallButton" onclick="chooseOrder('semiOrder')">关联半成品加工单</span>
                <span class="smallButton" onclick="chooseOrder('material')">选择物料</span>
    <!--                         <input id="barcode" style="margin-left: 20px" type="text" class="text" placeholder="输入或扫码"/>-->
    <!--                         <label class="checkbox"><input id="cancel_button" type="checkbox" ><span></span>&nbsp;撤销</label>-->
efo;
        $line = query('product_line', "id = '$info[lineId]'");
        //表单
        $data['button'] = $this->tableShowButton($button);
        $body = $this->edit4([
            '基本信息' => [
                [
                    must . "生产线：" => repeatSelect(array(
                            'name' => 'workshop',
                            'title' => '生产车间',
                            'change' => "getLine",
                            'sqlForm' => "product_line where coid = '" . self::$coid . "' and state = '启用'",
                            'sqlField' => 'workshop',
                            'value' => $line['workshop']
                        )) .
                        idSelect(array(
                            'name' => 'lineId',
                            'sqlForm' => "product_line where coid = '" . self::$coid . "' and state = '启用' and workshop = '$line[workshop]'",
                            'change' => 'getPickId',
                            'sqlId' => 'id',
                            'sqlField' => 'name',
                            'title' => '生产线',
                            'value' => $info['lineId']
                        )),
                    must . "领料人：" => "<div id='pickId' style='flex: 1'>" .
                        selectMultiple(["name" => "pickId", "value" => $info['pickId'], 'table' => "staff", 'sqlId' => 'stid', 'sqlField' => 'name', 'title' => '请选择']) .
                        "</div>",
                    must . "单据日期：" => text(["name" => "recordDate", 'laydate' => [], "value" => $info['recordDate'] ?: $this->date]),
                ],
                [

                    "备注：" => textarea(["name" => "text", "value" => $info['text']]),
                ],
            ]
        ]);
        $body .= $this->editList([
            'id' => 'materialTable',
            'title' => '领料明细',
            'button' => $but,
            'html' => $table,
        ]);
        $data['html'] = $this->pageEdit([
            "html" => $body,
            'hidden' => hidden(['name' => 'id', 'value' => $id]),
        ]);
        $data['html'] .= $this->js() . $this->style();
        //返回
        return $this->tab($data);
    }

    /**
     * 根据条码获取属性ID
     */
    public function getMaterial(): bool|string
    {
        if (empty($this->post('code'))) {
            $json['warn'] = "未找到条码";
        } else {
            $material = query('material', "barcode = '" . $this->post('code') . "' and coid = '" . self::$coid . "'");
            $json['data'] = $material['id'];
            $json['warn'] = 2;
        }
        return json_encode($json, 320);
    }

    /**
     * 默认领料人
     * @return bool|string
     */
    public function getPickId(): bool|string
    {
        $json['warn'] = 2;
        $line = query('product_line', "id = '" . $this->post('lineId') . "'");
        $json['html'] = selectMultiple(["name" => "pickId", "value" => $line['staffId'], 'table' => "staff", 'sqlId' => 'stid', 'sqlField' => 'name', 'title' => '请选择']);
        return json_encode($json, 320);
    }

    /**
     * JS
     * @return string
     */
    public function js(): string
    {
        $cla = self::page;
        return <<<eof
<script>
function chooseOrder(classify=''){
    if (classify !=='material' && !$("[name='lineId']").val()){
        msg('请先选择生产线','error')
        return false;
    }
    if (classify==='machiningOrder'){
        layer('{$this->get('cla')}','addOrder',$('form[name=pickOrderEditForm]').serialize())
    }
    if(classify==='semiOrder'){
        layer('{$this->get('cla')}','addSemiOrder',$('form[name=pickOrderEditForm]').serialize())
    }
    if(classify==='material'){
        layer('{$this->get('cla')}','addMx',$('form[name=pickOrderEditForm]').serialize())
    }
}
//获取领料人
function getPickId(e){
    let lineId = e.value;
      $.post(root+'control/adIndex.html?cla={$cla}&fun=getPickId',{lineId:lineId},function(res) {
         if (res.warn===2){
              $("#pickId").empty().append(res.html);
          }else{
              msg(res.warn,'error');
          }
     },'json')
}
/***扫码操作***/
$("#barcode").on('keydown',function(event) {
    if (event.keyCode==13){
        let code = $(this).val();//条码
        if (!code){
            msg('未找到条码','error')
            return '';
        }
        //判断是否是撤销操作
        if ($("#cancel_button").is(":checked")){
            //撤销
            $.post(root+'control/adIndex.html?cla={$cla}&fun=getMaterial',{code:code},function(res) {
                  if (res.warn===2){
                      $("#materialTable").find("input[name='materialId[]']").each(function() {
                           if (res.data === $(this).val()){
                               $(this).parent().parent().remove();
                           }
                      });
                  }else{
                      msg(res.warn,'error');
                  }
            },'json')
        }else{
            //添加
             $.post(root+'control/adIndex.html?cla={$cla}&fun=getMaterial',{code:code},function(res) {
                 if (res.warn===2){
                       $.post(root+'control/adIndex.html?cla={$cla}&fun=addMxEdit',{materialId:res.data,classify:'barcode'},function(res) {
                           if (res.warn ==2){
                               $("#materialTable tbody").append(res.html);
                               resetNumber($("#materialTable"))
                               calculateTotal()
                           }else{
                               msg(res.warn,'error');
                           }
                           
                       },'json')
                  }else{
                      msg(res.warn,'error');
                  }
             },'json')
        }
    }
});

//获取当前可用库存
function getInventory(e){
    let obj = $(e).parent().parent();
    let warehouseId = e.value;
    let materialId = obj.find("[name='materialId[]']").val();
    let unit = obj.find("[name='unitDetail[]']").val();
    if (!warehouseId){
        msg('请选择仓库');
        obj.find(".inventory").html('');
    }else if(!materialId){
         msg('未找到物料');
        obj.find(".inventory").html('');
    }else if(!unit){
         msg('请选择单位');
        obj.find(".inventory").html('');
    }else{
        $.post(root+'control/adIndex.html?cla={$this->get('cla')}&fun=getInventory',{warehouseId:warehouseId,materialId:materialId,unit},function(res) {
              obj.find(".batchInventory").html(res.num);
              obj.find(".batch").html(res.batch);
        },'json');
    }
}
//获取批次库存
function getBatchInventory(e){
    let batch = e.value;
    let materialId = $(e).parents("td").parent().find("[name='materialId[]']").val();
    let warehouseId = $(e).parents("td").parent().find("[name='warehouseId[]']").val();
    let unit = $(e).parents("td").parent().find("[name='unitDetail[]']").val();
    $.post(root+'control/adIndex.html?cla={$cla}&fun=getBatchInventory',{warehouseId:warehouseId,materialId:materialId,batch:batch,unit:unit},function(res) {
          $(e).parents("td").parent().find(".batchInventory").html(res.inventory);
    },'json');
}
//根据单位转换所需数量和库存
function unitChange(e){
    let unit = e.value;
    if (!unit){
        msg('请选择单位')
        return '';
    }
    let oldUnit = $(e).data('unit');
    $(e).data('unit',unit);
    let num = $(e).parent().parent().find("[name='num[]']").val();
    let id = $(e).parent().parent().find("[name='materialId[]']").val();
    $.post(root+'control/adIndex.html?cla={$this->get('cla')}&fun=unitChange',{unit:unit,oldUnit:oldUnit,num:num,id:id},function(res) {
        if (res.warn==2){
            $(e).parent().parent().find("[name='num[]']").val(res.num);
            $(e).parent().parent().find(".inventory").html(res.inventoryNum);
        }else{
            msg(res.warn);
        }
    },'json');
}
//获取生产线
function getLine(e){
     let val = e.value;
     $.post(root+'control/adIndex.html?cla=machiningOrder&fun=getLine',{val:val},function(res) {
             $("select[name='lineId']").html(res.html);
        },'json');
}

function addRow(classify = ''){
    if (classify ==='purchaseApply'){
        $.post(root+'control/adIndex.html?cla={$this->get('cla')}&fun=addOrderEdit',$("form[name='saleOrderForm']").serialize(),function(res) {
            if (res.warn ==2){
                $("#materialTable tbody").append(res.html);
                resetNumber($("#materialTable"))
                calculateTotal()
            }else{
                 msg(res.warn,'error')
            }
            
        },'json');
    } else if(classify ==='semiOrder'){
         $.post(root+'control/adIndex.html?cla={$this->get('cla')}&fun=addSemiOrderEdit',$("form[name='semiOrderForm']").serialize(),function(res) {
            if (res.warn ==2){
               $("#materialTable tbody").append(res.html);
               resetNumber($("#materialTable"))
               calculateTotal()
            }else{
                msg(res.warn,'error')
            }
        },'json');
    }else{
         $.post(root+'control/adIndex.html?cla={$this->get('cla')}&fun=addMxEdit',$("form[name='mxForm']").serialize(),function(res) {
             if (res.warn ==2){
                $("#materialTable tbody").append(res.html);
                resetNumber($("#materialTable"))
                calculateTotal()
           }else{
               msg(res.warn,'error');
           }
            
        },'json');
    }
}
//计算计划数量
function calculateTotal(table=''){
    table = table ? table : $('.editList')
    let num = 0
    table.find("[name='num[]']").each(function(index){
        if($(this).val()){
          num+=Number($(this).val());
        }
    })
    $("#total_num").text(num.toFixed(publicSettings.numPrecision.num));
}
function warehouseCall() {
  $("select[name='warehouseId[]']").each(function() {
      getInventory(this);
    });
}
</script>
eof;

    }


    /**
     * 获取当前可用库存
     */
    public function getInventory(): bool|string
    {
        $warehouseId = $this->post('warehouseId');
        $materialId = $this->post('materialId');
        $unit = $this->post('unit');
        //当前可用库存
        $batchOption = toolOverhaulOutClass::getBatchOption($materialId, $warehouseId, unit: $unit);
        $batch = array_key_first($batchOption)?:'';
        $inventoryNum = inventoryBalanceClass::inventoryNum($materialId, $warehouseId, batch: $batch);
        $inventoryNum = machiningOrderClass::material_num_change($materialId, toolOverhaulOutClass::getMainUnit($materialId), $unit, $inventoryNum);
        $json['num'] = self::formattingFigure($inventoryNum, 'numPrecision');
        //批号
        $json['batch'] = selectMultiple([
            "name" => "batch[]",
            'change' => 'getBatchInventory',
            'option' => $batchOption,
            'title' => '请选择',
            'value' => $batch,
        ]);
        return json_encode($json, 320);
    }

    /**
     * 获取批次库存
     */
    public function getBatchInventory(): bool|string
    {
        $warehouseId = $this->post('warehouseId');
        $materialId = $this->post('materialId');
        $batch = $this->post('batch');
        $unit = $this->post('unit');
        //当前批次库存
        $batchInventory = inventoryBalanceClass::inventoryNum($materialId, $warehouseId, batch: $batch);
        $batchInventory = machiningOrderClass::material_num_change($materialId, toolOverhaulOutClass::getMainUnit($materialId), $unit, $batchInventory);
        $json['inventory'] = $batchInventory;
        return json_encode($json, 320);
    }


    /**
     * 根据单位显示所需数量
     */
    public function unitChange()
    {
        $materialId = $this->post('id');
        $num = $this->post('num') ?: 0;
        $unit = $this->post('unit');
        $oldUnit = $this->post('oldUnit');
        if (!$this->power(self::page, "edit")) {
            $json['warn'] = "你没有编辑" . self::title . "的权限";
        } elseif (empty($materialId)) {
            $json['warn'] = '未找到物料';
        } elseif (empty($unit)) {
            $json['warn'] = '未找到单位';
        } else {
            $json['warn'] = 2;
            $inventoryNum = machiningOrderClass::inventory($materialId, $unit);
            $json['num'] = $num;
            $json['inventoryNum'] = $inventoryNum;
            if ($oldUnit) {
                $num = machiningOrderClass::material_num_change($materialId, $oldUnit, $unit, $num);
                $json['num'] = $num;
            }
        }

        return json_encode($json, 320);
    }

    /**
     * 计算库存占用量
     * @param $id string 领料单ID
     * @param $warehouseId
     * @param $materialId
     * @param $unit
     * @return float
     */
    private function occupy($id, $warehouseId, $materialId, $unit): float
    {
        //未完全出库及未出库的领料总数量
        $pickOrderMx = find(array(
            'table' => "pick_order_detail as a join pick_order as b on a.orderId = b.id join inventory as c on c.sourceId = b.id",
            'where' => "b.state = '已确认' and b.type=0 and a.warehouseId = '$warehouseId' and a.coid = '" . self::$coid . "' and a.materialId = '$materialId' and c.state !='已出库' and b.id !='$id'",
            'field' => "a.num,a.unit"
        ));
        //每一个领料单明细单位都可能不同，所以需要统一为主单位再看需求是否需要转为其他单位
        $pickNum = 0;
        foreach ($pickOrderMx['array'] as $array) {
            $pickNum += machiningOrderClass::material_num_change($materialId, $array['unit'], $unit, $array['num']);
        }
        //出库单中已出库的数量
        $outNum = 0;
        $inventoryMxAll = find(array(
            'table' => 'inventory_detail as a join inventory as b on a.orderId = b.id', 'field' => "a.num,a.unit",
            'where' => "b.state in ('待出库','部分出库')  and b.warehouseId = '$warehouseId' and a.coid = '" . self::$coid . "' and a.materialId = '$materialId' and b.classify=0 and b.sourceTable = '" . self::table . "'"
        ));
        foreach ($inventoryMxAll['array'] as $array) {
            $outNum += machiningOrderClass::material_num_change($materialId, $array['unit'], $unit, $array['num']);
        }
        return self::formattingFigure($pickNum - $outNum, 'numPrecision');
    }

    /**
     * 保存并提交
     * @return bool|string
     */
    public function saveAndCommit(): bool|string
    {
        $resultJson = $this->editEdit();
        $result = json_decode($resultJson,true);
        if ($result['warn'] == 2){
            unset($_SESSION['warn']);
            $resultJson = $this->commitEdit();
        }
        return $resultJson;
    }

    public function editEdit()
    {
        $id = $this->post('id') ?: self::getId();
        $mxIdArr = $this->post('mxId') ?: [];
        $materialIdArr = $this->post('materialId');
        $sourceIdArr = $this->post('sourceId');
        $numArr = $this->post('num');
        $batchArr = $this->post('batch');
        $unitArr = $this->post('unitDetail');
        $mxTextArr = $this->post('mxText');
        $warehouseIdArr = $this->post('warehouseId');

        $field = [
            'text' => $this->post('text'),
            'lineId' => $this->post('lineId'),
            'pickId' => $this->post('pickId'),
            'recordDate' => $this->post('recordDate'),
        ];
        $where = " id = '$id' ";
        $info = query(self::table, $where);
        //判断
        if (!$this->power(self::page, "edit")) {
            $json['warn'] = "你没有编辑" . self::title . "的权限";
        } elseif (!empty($info['id']) && $info['state'] == '已确认') {
            $json['warn'] = '此领料单已确认，不能修改';
        } else {
            $json['warn'] = '';
            //选项控制---按照生产加工单严格执行领料
            if (optionSettingClass::getSettingItem('生产', 'machiningOrderStrict')) {
                foreach ($mxIdArr as $index => $mxId) {
                    if (isset($sourceIdArr[$index]) && static::total(array('table' => 'machining_order_detail', 'where' => "id = '$sourceIdArr[$index]'")) > 0) {
                        $machining_order_detail = query('machining_order_detail', "id = '$sourceIdArr[$index]'");
                        //已领料的数量
                        $all = find(array(
                            'table' => 'pick_order_detail as a join pick_order as b on a.orderId = b.id',
                            'field' => "a.*",
                            "where" => "a.sourceId = '$sourceIdArr[$index]' and b.id !='$id' and b.type=0  and a.coid = '" . self::$coid . "'"
                        ));
                        $num = 0;
                        foreach ($all['array'] as $array) {
                            $num += machiningOrderClass::material_num_change($array['materialId'], $array['unit'], $unitArr[$index], $array['num']);
                        }
                        $machining_order_detail['quantity'] = machiningOrderClass::material_num_change(
                            $machining_order_detail['materialId'],
                            $machining_order_detail['unit'],
                            $unitArr[$index],
                            $machining_order_detail['quantity']
                        );
                        $material = query('material', "id = '$machining_order_detail[materialId]'");
                        if (self::formattingFigure($num + $numArr[$index], 'numPrecision') > $machining_order_detail['quantity']) {
                            $json['warn'] = "物料【{$material['name']}】的领料数量已超出订单所需物料数量";
                            break;
                        }
                    }
                }
            }

            if (empty($json['warn'])) {
                $this->startTrans();
                $isPass = true;//事务通过标志
                if (!$info['id']) {
                    $userNo = codeTemplateClass::generateCode(self::page, [
                        'prefix' => 'LLDD' . date('Ymd', strtotime($field['recordDate'])),
                        'table' => self::table,
                        'field' => 'orderNo',
                        'where' => "and coid = '" . self::$coid . "'",
                    ], $field);
                    $field = array_merge($field, [
                        'id' => $id,
                        'orderNo' => $userNo,
                        'state' => '草稿',
                        'coid' => self::$coid,
                        'stid' => $this->control['stid'],
                    ]);
                    $json['warn'] = static::insert(["table" => self::table, "field" => $field]);
                } else {
                    $json['warn'] = static::update([
                        "table" => self::table,
                        "field" => $field,
                        "where" => $where
                    ]);
                }

                //添加或更新明细
                if (is_array($mxIdArr)) {
                    foreach ($mxIdArr as $k => $nid) {
                        $mx = query(self::tableMx, "id = '$nid'");
                        $numArr[$k] = self::formattingFigure($numArr[$k], 'numPrecision');
                        if (!empty($mx['id'])) {
                            //更新
                            $warn = static::update([
                                "table" => self::tableMx,
                                "field" => [
                                    'sourceId' => $sourceIdArr[$k],
                                    'materialId' => $materialIdArr[$k],
                                    'num' => $numArr[$k],
                                    'batch' => $batchArr[$k],
                                    'unit' => $unitArr[$k],
                                    'warehouseId' => $warehouseIdArr[$k],
                                    'text' => $mxTextArr[$k],
                                ],
                                "where" => " id = '$nid'"
                            ]);
                        } else {
                            //新增
                            $warn = static::insert([
                                "table" => self::tableMx,
                                "field" => [
                                    'id' => $nid,
                                    'orderId' => $id,
                                    'coid' => self::$coid,
                                    'sourceId' => $sourceIdArr[$k],
                                    'sourceTable' => $sourceIdArr[$k] ? 'machining_order_detail' : '',
                                    'materialId' => $materialIdArr[$k],
                                    'num' => $numArr[$k],
                                    'batch' => $batchArr[$k],
                                    'unit' => $unitArr[$k],
                                    'warehouseId' => $warehouseIdArr[$k],
                                    'text' => $mxTextArr[$k],
                                ],

                            ]);
                        }
                        if (!in_array($warn, ['新增成功', '更新成功'])) {
                            $isPass = false;
                            $json['warn'] = $warn;
                            break;
                        }
                    }
                }

                if (in_array($json['warn'], ["新增成功", "更新成功"]) && $isPass) {
                    $this->commitTrans();
                    delete(array('table' => self::tableMx, 'where' => " id not in ('" . implode("','", $mxIdArr) . "') and orderId = '$id'"));
                    if ($json['warn'] == '新增成功') {
                        self::insertOperateLog($id,self::title,"新建");
                    }

                    //添加日志
                    $type = mb_substr($json['warn'], 0, 2, 'utf-8');
                    $text = $this->control['name'] . $type . "了" . self::title . " id：【" . $id . '】';
                    $this->logText(["type" => self::page, "text" => $text]);
                    //返回
                    $_SESSION['warn'] = $json['warn'];
                    $json['warn'] = 2;
                    $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $id;
                } else {
                    $this->rollback();
                }
            }
        }

        resp:
        return json_encode($json, 320);
    }

    /**
     * 关联半成品加工单
     */
    public function addSemiOrder()
    {
        $layerId          = $this->get('cla') . ucwords($this->get('fun'));
        $html =
            text(array("name" => "orderNo", "title" => "半成品加工单号")) .
            text(array("name" => "code", "title" => "物料编码")) .
            text(array("name" => "name", "title" => "物料名称")) .
            text(array("name" => "recordDate", 'class' => 'width200', 'laydate' => ['type' => 'date', 'range' => '~'], "title" => "单据日期-单据日期")) .
            hidden(array('name' => 'id', 'value' => $this->post('id'))) .
            hidden(array('name' => 'lineId', 'value' => $this->post('lineId'))) .
            hidden(array('name' => 'sourceId', 'value' => $this->post('sourceId') ? implode(',', $this->post('sourceId')) : ''));
        $button = "<input onclick=\"addRow('semiOrder');$('#" . $layerId . "').remove()\" type='button' class='searchSub m-l-5' value='提交'>";
        $html = $this->search($html);
        return $this->layer(array("title" => "添加", "height" => 600, "width" => 1000, "html" => $html, "button" => $button));
    }

    public function addSemiOrderSearch()
    {
        return $this->addOrderSearch('半成品');
    }

    public function addSemiOrderEdit()
    {
        $id = $this->post('id');
        $mxIdArr = $this->post('machiningOrderDetailId');
        if (!$this->power(self::page, 'edit')) {
            $json['warn'] = '你还没有编辑权限';
        } elseif (empty($mxIdArr) || !is_array($mxIdArr)) {
            $json['warn'] = '请选择半成品加工单';
        } else {
            $tr = [];
            foreach ($mxIdArr as $machiningOrderDetailId) {
                $machiningOrderMx = query('machining_order_detail', "id = '$machiningOrderDetailId'");
                $machiningOrder = query('machining_order', "id = '$machiningOrderMx[orderId]'");
                $material = query('material', "id = '$machiningOrderMx[materialId]'");
                $unitOption = machiningOrderClass::unitOption($material['id']);
                $select = select(array(
                    'name' => 'unitDetail[]',
                    'data' => ['unit' => $machiningOrderMx['unit']],
                    'change' => 'unitChange',
                    'option' => $unitOption,
                    'title' => '单位',
                    'value' => $machiningOrderMx['unit']
                ));
                //仓库选项
                $warehouse =select(array(
                    'name' => 'warehouseId[]',
                    'option' => toolOverhaulOutClass::warehouseOption($machiningOrderMx['materialId'], $machiningOrderMx['unit']),
                    'change' => 'getInventory',
                    'title' => '仓库'
                ));
                $orderNum = $this->pickedMaterialNum($machiningOrderMx['id'], $machiningOrderMx['unit'], $id);
                $num = ($machiningOrderMx['quantity'] - $orderNum) > 0 ? self::formattingFigure($machiningOrderMx['quantity'] - $orderNum, 'numPrecision') : 0;

                $suiji = self::getId();
                $tr[] = [
                    componentClass::tablePperation('',"delTableRow(this);calculateTotal()").
                    hidden(array('name' => 'mxId[]', 'value' => $suiji)) .
                    hidden(array('name' => 'materialId[]', 'value' => $material['id'])) .
                    hidden(array('name' => 'sourceId[]', 'value' => $machiningOrderMx['id'])),
                    $material['subject'],
                    $material['code'],
                    $material['name'],
                    $material['model'],
                    $select,
                    $warehouse,
                    "<span class='batch'>" .
                        selectMultiple([
                            "name" => "batch[]",
                            'option' => toolOverhaulOutClass::getBatchOption($material['id'], ''),
                            'title' => '请选择',
                            'change' => 'getBatchInventory',
                            'value' => ''
                        ]) .
                    "</span>",
                    "<span class='batchInventory'></span>",
                    text(array('name' => 'num[]', 'other' => self::digitalFiltering('numPrecision')." onblur=\"calculateTotal()\" ", 'value' => $num)),
                    '半成品加工单',
                    $machiningOrder['orderNo'],
                    text(array('name' => 'mxText[]', 'class' => 'text textPrice')),
                ];
            }
            if (empty($tr)) {
                $json['warn'] = '所选单据中无待领料明细';
            } else {
                $json['warn'] = 2;
                $json['html'] = $this->tableMany(['tr' => $tr, 'thead' => false]);
            }
        }
        return json_encode($json, 320);
    }

    /**
     * 关联生产计划单
     * @return bool|string
     */
    public function addOrder(): bool|string
    {
        $layerId          = $this->get('cla') . ucwords($this->get('fun'));
        $formName         = 'saleOrderForm';
        $html =
            text(array("name" => "orderNo", "title" => "生产计划单号")) .
            text(array("name" => "code", "title" => "物料编码")) .
            text(array("name" => "name", "title" => "物料名称")) .
            text(array("name" => "recordDate", 'class' => 'width200', 'laydate' => ['type' => 'date', 'range' => '~'], "title" => "单据日期-单据日期")) .
            hidden(array('name' => 'id', 'value' => $this->post('id'))) .
            hidden(array('name' => 'lineId', 'value' => $this->post('lineId'))) .
            hidden(array('name' => 'sourceId', 'value' => $this->post('sourceId') ? implode(',', $this->post('sourceId')) : ''));
//        $button .= "<input onclick=\"addRow('purchaseApply');removeSelectedContent('" . $formName . "')\" type='button' class='searchSub m-l-5' value='继续添加'>";
        $button = "<input onclick=\"addRow('purchaseApply');$('#" . $layerId . "').remove()\" type='button' class='searchSub m-l-5' value='提交'>";
        $html = $this->search($html);
        return $this->layer(array("title" => "添加", "height" => 600, "width" => 1000, "html" => $html, "button" => $button));
    }

    /**
     * 关联生产计划单
     * @param string $orderType
     * @return bool|string
     */
    public function addOrderSearch($orderType = '生产计划'): bool|string
    {
        $sourceId = $this->post('sourceId') ? explode(',', $this->post('sourceId')) : [];
        //只显示领料的，去除掉配料需求中的物料
        $and = " 
        and b.id not in  ('" . implode("','", $sourceId) . "') 
        and isClose = 0 
        and b.materialId not in (select materialId from ingredients_demands where machiningOrderId = a.id)";//
        $like = [
            'a.orderNo' => $this->post('orderNo'),
            'c.name' => $this->post('name'),
            'c.code' => $this->post('code'),
        ];
        $equal = [
            'orderType' => $orderType,
            'a.state' => '已确认',
            'a.coid' => self::$coid,
            'a.lineId' => $this->post('lineId')
        ];
        if ($this->post('recordDate')) {
            //单据日期
            $and .= self::timeComparison($this->post('recordDate'), field: 'a.recordDate');
        }
        $where = search(["like" => $like, "=" => $equal]) . $and;
        $page = $this->page([
            "table" => "machining_order as a join machining_order_detail as b on a.id = b.orderId join material as c on b.materialId = c.id",
            "where" => $where,
            'pageNum' => 50,
            "order" => "a.recordDate desc,a.orderNo desc,b.list",
            'field' => "b.*,a.orderNo,a.recordDate,a.lineId,c.name,c.code,c.model"
        ]);
        //获取表头
        $formName = 'saleOrderForm';
        if ($orderType == '半成品') {
            $formName = 'semiOrderForm';
        }
        $checkAll = $this->checkAll($formName, "machiningOrderDetailId");
        $tr[] = [$checkAll, '生产计划单号', '生产线', '单据日期', '产品编码', '产品名称', '规格型号', '单位', '未领料数量'];
        //获取记录
        foreach ($page['array'] as $array) {
            $dominate = array(
                "box" => array("name" => "machiningOrderDetailId", "value" => $array['id']),
            );
            $line = query('product_line', "id = '$array[lineId]'");
            $orderNum = $this->pickedMaterialNum($array['id'], $array['unit'], $this->post('id'));
            $tr[] = array(
                $this->dominate($dominate),
                $array['orderNo'],
                $line['workshop'] . '-' . $line['name'],
                $array['recordDate'],
                $array['code'],
                $array['name'],
                $array['model'],
                $array['unit'],
                self::lostZero($array['quantity'] - $orderNum, 'numPrecision')
            );
        }
        $json['html'] = $page['hint'] .
            "<form name='{$formName}'>" .
                hidden(array('name' => 'id', 'value' => $this->post('id'))) .
                $this->tableMany(array("tr" => $tr, "showSort" => true, "page" => $page['para'])) .
            "</form>" .
            $page['button'];
        return json_encode($json, 320);
    }

    /**
     * 已进入领料单的数量
     * @param $machiningOrderDetailId
     * @param $unit
     * @param $id
     * @return float|int
     */
    public function pickedMaterialNum($machiningOrderDetailId, $unit, $id)
    {
        $pick_order_detailAll = find(array(
            'table' => 'pick_order_detail',
            'where' => "orderId !='$id' and sourceId = '$machiningOrderDetailId' and coid = '" . self::$coid . "'"
        ));
        $orderNum = 0;//已进进入领料单的生产计划单明细数量
        foreach ($pick_order_detailAll['array'] as $array) {
            $orderNum += machiningOrderClass::material_num_change($array['materialId'], $array['unit'], $unit, $array['num']);
        }
        return $orderNum;
    }

    /**
     * 关联生产计划单
     */
    public function addOrderEdit()
    {
        $id = $this->post('id');//采购订单ID
        $mxIdArr = $this->post('machiningOrderDetailId');
        if (!$this->power(self::page, 'edit')) {
            $json['warn'] = '你还没有编辑权限';
        } elseif (empty($mxIdArr) || !is_array($mxIdArr)) {
            $json['warn'] = '请选择生产计划单的所需物料';
        } else {
            $tr = [];
            foreach ($mxIdArr as $machiningOrderDetailId) {
                $machiningOrderMx = query('machining_order_detail', "id = '$machiningOrderDetailId'");
                $machiningOrder = query('machining_order', "id = '$machiningOrderMx[orderId]'");
                $material = query('material', "id = '$machiningOrderMx[materialId]'");
                //单位选项
                $unitOption = machiningOrderClass::unitOption($material['id']);
                $orderNum = $this->pickedMaterialNum($machiningOrderMx['id'], $machiningOrderMx['unit'], $id);
                $num = ($machiningOrderMx['quantity'] - $orderNum) > 0 ? self::formattingFigure($machiningOrderMx['quantity'] - $orderNum, 'numPrecision') : 0;
                $suiji = self::getId();
                $tr[] = [
                    componentClass::tablePperation('',"delTableRow(this);calculateTotal()").
                    hidden(array('name' => 'mxId[]', 'value' => $suiji)) .
                    hidden(array('name' => 'materialId[]', 'value' => $machiningOrderMx['materialId'])) .
                    hidden(array('name' => 'sourceId[]', 'value' => $machiningOrderMx['id'])),
                    $material['subject'],
                    $material['code'],
                    $material['name'],
                    $material['model'],
                    select(array(
                        'name' => 'unitDetail[]',
                        'data' => ['unit' => $machiningOrderMx['unit']],
                        'change' => 'unitChange',
                        'option' => $unitOption,
                        'title' => '单位',
                        'value' => $machiningOrderMx['unit']
                    )),
                    select(array(
                        'name' => 'warehouseId[]',
                        'option' => toolOverhaulOutClass::warehouseOption($machiningOrderMx['materialId'], $machiningOrderMx['unit']),
                        'change' => 'getInventory',
                        'title' => '仓库'
                    )),
                    "<span class='batch'>" .
                        selectMultiple([
                            "name" => "batch[]",
                            'option' => toolOverhaulOutClass::getBatchOption($material['id'], ''),
                            'title' => '请选择',
                            'change' => 'getBatchInventory',
                            'value' => ''
                        ]) .
                    "</span>",
                    "<span class='batchInventory'></span>",
                    text(array('name' => 'num[]', 'other' => self::digitalFiltering('numPrecision')." onblur=\"calculateTotal()\" ", 'value' => $num)),
                    '生产计划单',
                    $machiningOrder['orderNo'],
                    text(array('name' => 'mxText[]', 'class' => 'text textPrice')),
                ];
            }
            if (empty($tr)) {
                $json['warn'] = '所选单据中无待领料明细';
            } else {
                $json['html'] = $this->tableMany(['tr' => $tr, 'thead' => false]);
                $json['warn'] = 2;
            }
        }
        return json_encode($json, 320);
    }


    /**
     *
     * @return bool|string
     */
    public function addMx()
    {
        $materialClassObj = new materialClass();
        $layerId          = $this->get('cla') . ucwords($this->get('fun'));
        $formName         = 'mxForm';
        $notAllowRepeat   = 1;
        $data             = [
            'sub'            => " onclick=\"addRow();$('#" . $layerId . "').remove()\" ",
            'continueAdding' => $notAllowRepeat ? " onclick=\"addRow();removeSelectedContent('" . $formName . "')\" " : " onclick=\"addRow();\" ",
            'hidden'         => hidden(["name" => "notAllowRepeat", "value" => $notAllowRepeat]) .
                hidden(["name" => "supplyControl", "value" => '允许采购']) .
                hidden(array('name' => 'materialId', 'value' => $this->post('materialId') ? implode(',', $this->post('materialId')) : '')),
        ];
        return $materialClassObj->addMx($data);
    }

    /**
     * 编辑
     *
     * @return bool|string
     */
    public function addMxEdit()
    {
        $mxIdArr = $this->post('mxId');
        $materialId = $this->post('materialId');
        $classify = $this->post('classify');//扫码添加类型
        if (!$this->power(self::page, 'edit')) {
            $json['warn'] = '你还没有编辑权限';
        } elseif ($classify !== 'barcode' && (empty($mxIdArr) || !is_array($mxIdArr))) {
            $json['warn'] = '请选择物料';
        } elseif ($classify === 'barcode' && empty($materialId)) {
            $json['warn'] = '未找到物料';
        } else {

            if ($classify === 'barcode') {
                $mxIdArr[] = $materialId;
            }
            $tr = [];
            foreach ($mxIdArr as $mxId) {
                $material = query('material', "id = '$mxId'");
                $unitOption = machiningOrderClass::unitOption($material['id']);
                //仓库选项
                $suiji = self::getId();
                $tr[] = [
                    componentClass::tablePperation('',"delTableRow(this);calculateTotal()").
                    hidden(array('name' => 'mxId[]', 'value' => $suiji)) .
                    hidden(array('name' => 'materialId[]', 'value' => $mxId)) .
                    hidden(array('name' => 'sourceId[]')),
                    $material['subject'],
                    $material['code'],
                    $material['name'],
                    $material['model'],
                    select(array(
                        'name' => 'unitDetail[]',
                        'data' => ['unit' => $material['unit']],
                        'change' => 'unitChange',
                        'option' => $unitOption,
                        'title' => '单位',
                        'value' => $material['unit']
                    )),
                    select(array(
                        'name' => 'warehouseId[]',
                        'option' => toolOverhaulOutClass::warehouseOption($mxId, $material['unit']),
                        'change' => 'getInventory',
                        'title' => '仓库'
                    )),
                    "<span class='batch'>" .
                        selectMultiple([
                            "name" => "batch[]",
                            'option' => toolOverhaulOutClass::getBatchOption($material['id'], ''),
                            'title' => '请选择',
                            'change' => 'getBatchInventory',
                            'value' => ''
                        ]) .
                    "</span>",
                    "<span class='batchInventory'></span>",
                    text(array('name' => 'num[]', 'other' => self::digitalFiltering('numPrecision')." onblur=\"calculateTotal()\" ")),
                    '',
                    '',
                    text(array('name' => 'mxText[]', 'class' => 'text textPrice')),
                ];
            }
            $json['warn'] = 2;
            $json['html'] = $this->tableMany(['tr' => $tr, 'thead' => false]);
        }
        return json_encode($json, 320);
    }

    /**
     * 显示类型
     * @param $type
     * @return string
     */
    public function orderType($type): string
    {
        return match ($type) {
            '半成品' => '半成品加工单',
            default => '生产计划单',
        };
    }

    /*详情页*/
    public function detail(): string
    {
        $info = query(self::table, " id = '{$this->get('id')}'");
        if (empty($info['id'])) {
            $html = '未找到此' . self::title;
        } else {

            //菜单
            $data = array(
                "id" => $info['id'],
            );

            $button = [];
            if ($this->power(self::page, "confirm") && $info['state'] == '待确认') {
                $button[] = [
                    "name" => "复核",
                    "type" => "弹出层",
                    "cla" => $this->get('cla'),
                    "fun" => "operate",
                    "post" => ["act" => 'confirm', "id" => $info['id']],
                    'style' => 'li-btn-blue-bg',
                ];
            }
            if ($info['state'] == '草稿') {
                if ($this->power(self::page, "edit")) {
                    //按钮
                    $button[] = [
                        "name" => "提交",
                        "type" => "弹出层",
                        "cla" => $this->get('cla'),
                        "fun" => "operate",
                        "post" => ["act" => 'commit', "id" => $info['id']],
                        'style' => 'li-btn-blue-bg',
                    ];
                    //按钮
                    $button[] = [
                        "name" => "编辑",
                        "type" => "顶部页卡",
                        "title" => "编辑用户",
                        "url" => $this->root . "control/adIndex.html?cla={$this->get('cla')}&fun=edit&id=" . $info['id'],
                    ];
                }
                if ($this->power(self::page, "del")) {
                    //按钮
                    $button[] = [
                        "name" => "删除",
                        "type" => "弹出层",
                        "cla" => $this->get('cla'),
                        "fun" => "operate",
                        "post" => ["act" => 'del', "id" => $info['id']],
                    ];
                }

            }
            if ($this->power(self::page, 'print')) {
                //按钮
                $button[] = [
                    "name" => "打印",
                    "type" => "点击事件",
                    "fun" => "window.open('" . root . "control/adIndex.html?cla=" . self::page . "&fun=printPage&id={$info['id']}')",
                ];
            }


            if ($this->power(self::page, "confirm") && $info['state'] != '草稿') {
                $button[] = [
                    "name" => "撤回",
                    "type" => "弹出层",
                    "cla" => $this->get('cla'),
                    "fun" => "operate",
                    "post" => ["act" => 'cancel', "id" => $info['id']],
                ];
            }
            $button[] = [
                "name" => "单据追踪",
                "type" => "顶部页卡",
                "title" => "单据追踪",
                "url" => $this->root . "control/adIndex.html?cla=orderTrack&fun=home&orderType=领料单&id=" . $info['id'],
            ];
            //操作记录
            $button[] = self::operateLogBut($info['id'],1);

            $mergeArr = [];
            $tr[] = ['存货分类', '物料编码', '物料名称', '规格型号', '单位', "仓库", '数量', '批次', '源单类型', '关联源单', '备注'];
            $result = find(array('table' => self::tableMx, 'where' => "orderId = '$info[id]' order by list"));
            foreach ($result['array'] as $array) {
                $material = query('material', " id = '$array[materialId]'");
                $machiningOrderMx = query('machining_order_detail', "id = '$array[sourceId]'");
                $machiningOrder = query('machining_order', "id = '$machiningOrderMx[orderId]'");
                //当前可用库存
                //$inventoryNum = machiningOrderClass::inventory($array['materialId'], $array['unit'], $array['warehouseId']);
                $warehouse = query('warehouse', "id = '$array[warehouseId]'");
                $tr[] = [
                    $material['subject'],
                    $material['code'],
                    $material['name'],
                    $material['model'],
                    $array['unit'],
                    $warehouse['name'],
                    self::lostZero($array['num'], 'numPrecision'),
                    $array['batch'],
                    $this->orderType($machiningOrder['orderType']),
                    $machiningOrder['orderNo'],
                    $array['text'],
                ];
                $mergeArr[$array['materialId']][$array['warehouseId']] = $mergeArr[$array['materialId']][$array['warehouseId']] ?? 0;
                $mergeArr[$array['materialId']][$array['warehouseId']] += machiningOrderClass::material_num_change($array['materialId'], $array['unit'], $material['unit'], $array['num']);
            }
            $total_tr = [
                6  => self::lostZero(array_sum(array_column((array)$result['array'],'num')),'num'),
            ];
            //合并物料
            $alltr[] = ['存货类型', '物料编码', '物料名称', '规格型号', '单位', "仓库", '领料数量'];
            $totalNum = 0;
            foreach ($mergeArr as $materialId => $array) {
                foreach ($array as $warehouseId => $num) {
                    $material = query('material', " id = '$materialId'");
                    $warehouse = query('warehouse', "id = '$warehouseId'");
                    $firstMx = query(self::tableMx, "orderId = '$info[id]' and materialId = '$materialId' order by list");
                    $pick_num = machiningOrderClass::material_num_change($materialId, $material['unit'], $firstMx['unit'], $num);
                    $alltr[] = [
                        $material['subject'],
                        $material['code'],
                        $material['name'],
                        $material['model'],
                        $firstMx['unit'],
                        $warehouse['name'],
                        $pick_num
                    ];
                    $totalNum += $pick_num;
                }
            }
            $total_all = [
                6 => $totalNum
            ];
            $line = query('product_line', "id = '$info[lineId]'");
            //生成表单
            $data['button'] = $this->tableShowButton($button);
            $data['html'] = $this->tableShow(array(
                '详细信息' => array(
                    array(
                        "生产线" => $line['workshop'] . '-' . $line['name'],
                        "领料人" => self::findStaff($info['pickId']),
                        "单据日期" => $info['recordDate'],
                        "单据编号" => $info['orderNo'],
                    ),
                    array(
                        "制单人" => self::findStaff($info['stid']),
                        "状态" => $info['state']
                    ),
                    array(
                        "备注" => pre($info['text']),
                    ),
                ),
            ));
            $data['html'] .= $this->detailList([
                'title' => '领料明细',
                'html' => $this->listTable(array('tr' => $tr, 'showSort' => true, 'total' => $total_tr)),
            ]);
            $data['html'] .= $this->detailList([
                'title' => '领料汇总',
                'html' => $this->listTable(array('tr' => $alltr, 'showSort' => true, 'total' => $total_all)),
            ]);
            //生成页面
            $html = $this->tab($data);
        }
        //返回
        return $html;
    }

    /**
     * 确认
     */
    public function confirmEdit()
    {
        $id = $this->post('id');
        $info = query(self::table, " id = '$id'");
        $field = [
            'state' => '已确认',
            'checkId' => self::$stid,
            'confirmTime' => $this->time
        ];
        $warn = '';
        $result = find(array('table' => self::tableMx, "where" => "orderId = '$id' order by list asc"));
        $tempResult = [];
        //判断库存是否可领料,首先需要相同物料分组，避免只判断一个物料够不够
        foreach ($result['array'] as $array) {
            $tempResult[$array['materialId']][$array['warehouseId']][$array['batch']][] = [
                'id' => $array['id'],
                'unit' => $array['unit'],
                'num' => $array['num'],
            ];
        }
        //库存可用量控制
        $inventorySetting = optionSettingClass::getSetting('库存');
        //判断对应批次的数量是否超出库存
        if (!$inventorySetting['outAllowZero']) { //不允许零库存出库
            foreach ($tempResult as $materialId => $array) {
                $material    = query('material', "id = '$materialId'", 'name,unit');
                foreach ($array as $warehouseId => $childRes) {
                    foreach ($childRes as $batch => $child) {
                        //当前库存
                        $batchInventory = inventoryBalanceClass::inventoryNum($materialId, $warehouseId, batch: $batch);
                        $num            = 0;
                        foreach ($child as $val) {
                            //领料主单位数量
                            $num += machiningOrderClass::material_num_change($materialId, $val['unit'], $material['unit'], $val['num']);
                        }
                        if ($num > $batchInventory) {
                            $warn = "物料【{$material['name']}】领料数量已超出库存数量";
                            break 3;
                        }
                    }
                }
            }
        }
        /*if (empty($warn) && isset($inventorySetting['inventoryCtrl']['option']) && $inventorySetting['inventoryCtrl']['option'] && in_array('inventoryOrder', (array)$inventorySetting['inventoryCtrl']['val'])) {
            foreach ($tempResult as $materialId => $array) {
                foreach ($array as $warehouseId => $childRes) {
                    $material = query('material', "id = '$materialId'");
                    //当前可用库存
                    $inventoryNum = machiningOrderClass::inventory($materialId, $material['unit'], $warehouseId);
                    $num = 0;
                    foreach ($childRes as $val) {
                        //占用库存
                        $num += machiningOrderClass::material_num_change($materialId, $val['unit'], $material['unit'], $val['num']);
                    }
                    if ($num > $inventoryNum) {
                        $warn = "物料【{$material['name']}】领料数量已超出可用库存数量";
                        break 2;
                    }
                }
            }
        }*/

        if (!$this->power(self::page, 'confirm')) {
            $json['warn'] = '你还没有确认权限';
        } elseif (empty($info['id'])) {
            $json['warn'] = '未找到此领料单';
        } elseif ($info['state'] != '待确认') {
            $json['warn'] = '此领料单不是待确认状态，不能确认';
        } elseif ($warn) {
            $json['warn'] = $warn;
        } else {
            $this->startTrans();
            $json['warn'] = update(array(
                "table" => self::table,
                "field" => $field,
                "where" => "id = '$info[id]'",
            ));
            $bool = $this->insertInventory($info);
            if ($bool !== true) {
                $json['warn'] = $bool;
            }
            if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                // 单据是否需要复核
                if(!in_array(self::page,self::$publicSettings['documentReview'])) {
                    self::insertOperateLog($info['id'],self::title,"提交、复核");
                }else{
                    self::insertOperateLog($info['id'],self::title,"复核");
                }
                $this->commitTrans();
                //添加日志
                $text = $this->control['name']  . "确认了" . self::title . "id：【" . $id . '】';
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = '确认成功';
                $json['warn'] = 2;
                $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $info['id'];
            } else {
                $this->rollback();
            }
        }
        resp:
        return json_encode($json, 320);
    }

    /**
     * 撤回
     */
    public function cancelEdit()
    {
        $id = $this->post('id');
        $info = query(self::table, " id = '$id'");
        $field = [
            'state' => '草稿',
            'checkId' => '',
            'confirmTime' => ''
        ];
        if (!$this->power(self::page, 'cancel')) {
            $json['warn'] = '你还没有撤回权限';
        } elseif (empty($info['id'])) {
            $json['warn'] = '未找到此领料单';
        } elseif ($info['state'] != '已确认') {
            $json['warn'] = '此领料单不是已确认状态，无需撤回';
        } elseif (static::total(array('table' => 'inventory', "where" => "sourceId = '$info[id]' and coid = '" . self::$coid . "' and state in ('部分出库','已出库')")) > 0) {
            $json['warn'] = '此领料单已存在有出库的单据，不能撤回';
        } else {
            $json['warn'] = update(array(
                "table" => self::table,
                "field" => $field,
                "where" => "id = '$info[id]'",
            ));
            if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                //删除出库单
                delete(array('table' => 'inventory_detail', 'where' => "orderId in (select id from inventory where sourceId = '$info[id]' and coid = '" . self::$coid . "')"));
                delete(array('table' => 'inventory', 'where' => "sourceId = '$info[id]'"));
                self::insertOperateLog($info['id'],self::title,"撤回");
                //添加日志
                $text = $this->control['name']  . "撤回了" . self::title . "id：【" . $id . '】';
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = '撤销成功';
                $json['warn'] = 2;
                $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $info['id'];
            }
        }
        resp:
        return json_encode($json, 320);
    }
    /**
     * Desc : 提交前数据验证
     * User : you name
     * Date : 2023-11-17 16:04
     * @param $info
     * @return string|bool
     */
    public function dataValidation($info): string|bool
    {
        $annotation = [
            'lineId' => '生产线',
            'pickId' => '领料人',
            'recordDate' => '单据日期',
        ];
        $rules = [
            'lineId' => 'required',
            'pickId' => 'required',
            'recordDate' => 'required|date',
        ];
        // 校验是否符合规则
        $vt = new \verify();
        $result = $vt->setAliases($annotation)->validate($info, $rules)->isOk();
        if ($result === false) {
            return $vt->getErrs()[0];  // 多个规则提示最前面一条
        }
        $result = find(array('table' => self::tableMx, 'field' => 'id,materialId,num,unit,warehouseId', 'where' => "orderId = '$info[id]' order by list"));
        if(count($result['array']) == 0){
            return "请完善领料明细";
        }
        if(static::is_null_array(array_column($result['array'],'materialId'))){
            return "领料明细中【属性】不能为空";
        }
        if(static::is_null_array(array_column($result['array'],'unit'))){
            return "领料明细中【单位】不能为空";
        }
        if(static::is_null_array(array_column($result['array'],'warehouseId'))){
            return "领料明细中【仓库】不能为空";
        }
        if(static::is_null_array(array_column($result['array'],'num'),false)){
            return "领料明细中【数量】不能为空，且必须大于0";
        }

        return true;
    }
    /**
     * 提交
     */
    public function commitEdit()
    {
        $id = $this->post('id');
        $info = query(self::table, " id = '$id'");
        $field = [
            'state' => '待确认',
        ];
        //提交前数据验证
        $json['warn'] = $this->dataValidation($info);
        if($json['warn'] !== true){
            goto resp;
        }
        if (!$this->power(self::page, 'edit')) {
            $json['warn'] = '你还没有编辑权限';
        } elseif (empty($info['id'])) {
            $json['warn'] = '未找到此领料单';
        } elseif ($info['state'] != '草稿') {
            $json['warn'] = '此领料单不是草稿状态，不能提交';
        } else {
            $this->startTrans();
            $json['warn'] = update(array(
                "table" => self::table,
                "field" => $field,
                "where" => "id = '$info[id]'",
            ));
            if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                // 单据是否需要复核
                if(!in_array(self::page,self::$publicSettings['documentReview'])){
                    $resultJson = $this->confirmEdit();
                    $json = json_decode($resultJson,true);
                    if ($json['warn'] != 2){
                        $this->rollback();
                        goto resp;
                    }
                }else {
                    self::insertOperateLog($info['id'],self::title,"提交");
                }
                $this->commitTrans();
                //添加日志
                $text = $this->control['name'] . "提交了" . self::title . "id：【" . $id . '】';
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = '提交成功';
                $json['warn'] = 2;
                $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $info['id'];
            } else {
                $this->rollback();
            }
        }
        resp:
        return json_encode($json, 320);
    }

    /**
     * 生成出库单
     */
    private function insertInventory($info): bool|string
    {
        $re_array = [];//根据仓库重新分组
        $result = find(array('table' => self::tableMx, 'where' => "orderId = '$info[id]' order by list asc"));
        foreach ($result['array'] as $array) {
            $re_array[$array['warehouseId']][] = $array['id'];
        }
        $index = 1;
        foreach ($re_array as $warehouseId => $array) {
            $id = self::getId();
            $field = [
                'id' => $id,
                'type' => '生产领料',
                'coid' => self::$coid,
                'sourceTable' => self::table,
                'sourceId' => $info['id'],
                'warehouseId' => $warehouseId,
                'targetId' => $info['lineId'],
                'classify' => 0,
                'state' => '待出库',
                'stid' => self::$stid,
                'orderDate' => $this->date,
                'sourceDate' => $info['recordDate'],
                'sourceNo' => $info['orderNo'],
                'sourceTargetName' => ''
            ];
            $userNo = codeTemplateClass::generateCode('outStock', [
                'prefix' => 'KCCK' . date('Ymd'),
                'table' => 'inventory',
                'field' => 'orderNo',
                'where' => " and coid = '" . self::$coid . "'",
                'index' => $index
            ], $field);
            $index++;
            $field['orderNo'] = $userNo;
            $warn = static::insert(array(
                'table' => 'inventory',
                'field' => $field
            ));
            if ($warn != '新增成功') {
                return "出库单新建失败";
            }
            foreach ($array as $mxId) {
                $mx = query(self::tableMx, "id = '$mxId'");
                $price = inventoryDefaultClass::pricingRules('outStockPrice', $mx['materialId'], $mx['unit']);
                $warn = static::insert(array(
                    'table' => 'inventory_detail',
                    'field' => [
                        'id' => self::getId(),
                        'coid' => self::$coid,
                        'sourceTable' => self::tableMx,
                        'sourceId' => $mx['id'],
                        'materialId' => $mx['materialId'],
                        'unit' => $mx['unit'],
                        'orderId' => $id,
                        'orderNum' => $mx['num'],
                        'batch' => $mx['batch'],
                        'warehouseId' => $mx['warehouseId'],
                        'price' => $mx['price']>0?$mx['price']:$price,
                        'money' => 0,
                    ]
                ));
                if ($warn != '新增成功') {
                    return "出库单明细新建失败";
                }
            }
        }
        return true;
    }

    // 操作中转
    public function operate()
    {
        $act = $this->post('act') ?? '';
        $pwd = $word = false; // 需要密码
        $form = $power = '';
        switch ($act) {
            case 'confirm':
                $act = 'confirm';
                $msg = '确认';
                $title = '是否已确认此领料单，确认后将不可修改？';
                $function = 'confirmEdit';
                $form = self::page . 'OperateForm, detailForm';
                $power = '';
                $word = true;
                break;
            case 'commit':
                $act = 'edit';
                $msg = '编辑';
                $title = '是否确认提交此领料单？';
                $function = 'commitEdit';
                $form = self::page . 'OperateForm, detailForm';
                $power = '';
                $word = true;
                break;
            case 'cancel':
                $act = 'cancel';
                $msg = '撤回';
                $title = '是否确认撤回此领料单？';
                $function = 'cancelEdit';
                $form = self::page . 'OperateForm, detailForm';
                $power = '';
                $word = true;
                break;
            default:
                $act = 'del';
                $msg = '删除' . self::title;
                $title = self::page . 'Delete';
                $function = 'delete';
                $form = self::page . 'OperateForm, listForm, quoForm';
                $power = '';
                break;
        }
        if (!$this->power(self::page, $act)) {
            $_SESSION['warn'] = '你还没有' . $msg . '的权限';
            $json = [
                'warn' => 2,
                'href' => root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=home',
            ];
        } else {
            return $this->confirm([
                'title' => $title,
                'function' => $function,
                'form' => $form,
                'power' => $power,
                'pwd' => $pwd,
                'word' => $word
            ]);
        }

        resp:
        return json_encode($json, 320);
    }

    /**
     * 删除
     * @return bool|string
     */
    public function delete()
    {
        $array = $this->post('listId') ?? $this->post('id');
        if (!$this->power(self::page, "del")) {
            $json['warn'] = "你没有删除的权限";
        } elseif (empty($array)) {
            $json['warn'] = "你一个数据都没有选择呢";
        } else {
            $text = "";
            $x = 0;
            $array = is_array($array) ? $array : [$array];
            foreach ($array as $id) {
                $info = query(self::table, " id = '$id' ");
                if ($info['state'] == '已确认') {
                    $warn = "删除失败：已确认，暂不能删除";
                } else {
                    //最后删除基本参数
                    delete(array("table" => self::table, "where" => " id = '$id' "));
                    delete(array("table" => self::tableMx, "where" => " orderId = '$id' "));
                    delete(array("table" => "auditing_follow", "where" => " typeId = '$id' "));
                    //返回
                    $warn = "删除成功";
                    $x++;
                }
                $text .= self::title . "ID【" . $info['id'] . "】" . $warn . "。<br>";
            }
            //添加日志
            $text = $this->control['name'] . "删除了" . self::title . "，结果如下：<br>" . $text;
            $this->logText(array("type" => self::page, "text" => $text));
            $_SESSION['warn'] = "删除了" . $x . "个" . self::title . "，详情见系统日志。";
            $json['warn'] = 2;
            $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=home";
        }
        return json_encode($json, 320);
    }

    /**
     * 样式
     * @return string
     */
    public function style(): string
    {
        return <<<eof
<style>
.stateBlock{margin-top: 0}
.stateBlock ul li{padding: 2px 10px}
.footer-ul-parent{float: right;margin-right: 10px}
.footer-ul li{margin-top: 10px}
.table-top-title{height: 30px;line-height: 30px;font-size: 14px;margin-top: 20px;}
.table-top-title>ul>li{float: left;width: 250px;}
</style>
eof;

    }

    /**
     * 打印
     */
    public function printPage(): string
    {

        $id = $this->get('id');
        $info = query(self::table, " id = '$id'");
        $info['companyName'] = query('company', "coid = '" . self::$coid . "'")['name']; //公司名称//公司名称
        $info['title'] = self::title;
        $info['printTime'] = $this->time;
        $info['stid'] = self::findStaff($info['stid']);
        $info['pickId'] = self::findStaff($info['pickId']);
        $line = query('product_line', "id = '$info[lineId]'");
        $info['lineName'] = $line['workshop'] . '-' . $line['name'];
        $info['qr'] = "source=" . self::table . "&id=" . $info['id'];
        $detail = find(['table' => self::tableMx, 'where' => "orderId = '$info[id]' order by list asc"])['array'];
        $items = [];
        $x = 1;
        $totalNum = 0;
        foreach ($detail as $array) {
            $material = query('material', "id = '$array[materialId]'");
            $warehouse = query('warehouse', "id = '$array[warehouseId]'");
            $items[] = [
                'no' => $x,
                'materialCode' => $material['code'],
                'materialName' => $material['name'],
                'model' => $material['model'],
                'unit' => $array['unit'],
                'num' => $array['num'],
                'text' => $array['text'],
                'warehouse' => $warehouse['name'],
            ];
            $x++;
            $totalNum += $array['num'];
        }
        $append = [
            'no' => '合计',
            'num' => self::lostZero($totalNum, 'amount'),
        ];
        $items[] = $append;
        $info['detail'] = $items;
        return (new printTemplateClass())->start(self::page, $info);
    }

    /**
     * 导入模板字段初始化
     * @return array[]
     */
    public function importFieldInit($classify=''): array
    {
        return match ($classify) {
            default=>  [
                [
                    'columnName'=>'单据编号',
                    'aliasName'=>'单据编号',

                    'isMust'=>false,
                ],
                [
                    'columnName'=>'单据日期',
                    'aliasName'=>'单据日期',

                    'isMust'=>true,
                ],
                [
                    'columnName'=>'生产线编号',
                    'aliasName'=>'生产线编号',

                    'isMust'=>true,
                ],
                [
                    'columnName'=>'生产线名称',
                    'aliasName'=>'生产线名称',

                    'isMust'=>false,
                ],
                [
                    'columnName'=>'领料人编号',
                    'aliasName'=>'领料人编号',

                    'isMust'=>false,
                ],
                [
                    'columnName'=>'领料人名称',
                    'aliasName'=>'领料人名称',

                    'isMust'=>false,
                ],
                [
                    'columnName'=>'单据备注',
                    'aliasName'=>'单据备注',

                    'isMust'=>false,
                ],
                [
                    'columnName'=>'物料名称',
                    'aliasName'=>'物料名称',

                    'isMust'=>true,
                ],
                [
                    'columnName'=>'规格型号',
                    'aliasName'=>'规格型号',

                    'isMust'=>true,
                ],
                [
                    'columnName'=>'仓库编码',
                    'aliasName'=>'仓库编码',

                    'isMust'=>false,
                ],
                [
                    'columnName'=>'仓库名称',
                    'aliasName'=>'仓库名称',

                    'isMust'=>false,
                ],
                [
                    'columnName'=>'单位',
                    'aliasName'=>'单位',

                    'isMust'=>true,
                ],
                [
                    'columnName'=>'数量',
                    'aliasName'=>'数量',

                    'isMust'=>true,
                ],
                [
                    'columnName'=>'单价',
                    'aliasName'=>'单价',

                    'isMust'=>false,
                ],
                [
                    'columnName'=>'批次',
                    'aliasName'=>'批次',

                    'isMust'=>false,
                ],
                [
                    'columnName'=>'备注',
                    'aliasName'=>'备注',

                    'isMust'=>false,
                ],
            ]
        };
    }
}

